package com.donar.nio.buffer;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Created by donar on 18/3/2.
 */
public class ScatterAndGather {
    public static void main(String[] args) throws IOException {
        RandomAccessFile file = new RandomAccessFile(ReadFile.class.getClassLoader().getResource("niotestdata.txt").getFile(),"rw");
        FileChannel channel = file.getChannel();
        int headLen = "this is Header".getBytes().length;
        int bodyLen = "this is Body".getBytes().length;
        //Gather 表示向channel中写数据的时候的数据聚合过程
        //ByteBuffer[] buffers = {ByteBuffer.wrap("this is Header".getBytes()),ByteBuffer.wrap("this is Body".getBytes())};
        //channel.write(buffers);
        //file.close();
        //Gather 表示向channel中写数据的时候的数据聚合过程
        ByteBuffer[] readBuffer = {ByteBuffer.allocate(headLen),ByteBuffer.allocate(bodyLen)};
        long i =0;
        while((i=channel.read(readBuffer))>0){
            readBuffer[0].flip();//buffer 读写模式切换
            while (readBuffer[0].hasRemaining()){ //buffer中还有未读完的数据的话继续读
                System.out.print((char)readBuffer[0].get()); //读取buffer中的数据并打印
            }
            System.out.println();
            readBuffer[1].flip();//buffer 读写模式切换
            while (readBuffer[1].hasRemaining()){ //buffer中还有未读完的数据的话继续读
                System.out.print((char)readBuffer[1].get()); //读取buffer中的数据并打印
            }
        }
        file.close();
    }
}
